// pages/index/index.js
const app = getApp()
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    listData: [],
  },
  opt:"",
  tab:'',
  pet:"",
  skip:1,
  bindViewTap: function () {
    wx.switchTab({
      url: '../index/index'
    })
  },
  getData:function(name,skip){
    db.collection(name)
      .skip(skip)
      .get({
        success: res => {
          this.skip +=20
          this.data.listData = this.data.listData.concat(res.data)
          this.setData({
            listData: this.data.listData
          })
        }
    })
  },
  onLoad: function (options) {
    this.opt = options
    // 连续两次setData此处逻辑需优化
    if(options.path=="load"){
      this.setData({show:false})
      if (options.type == "") {
        this.pet = 'dog'
        this.getData('dog',this.skip)
      }
      else {
        this.pet = options.type
        this.getData(options.type,this.skip)
      }
    }
    else{
      this.pet = options.type
      if (options.type == "cat") {
        this.tab = [["猫", '/img/cat.png', '/img/no-cat.png'], ["狗", '/img/Dog.png', '/img/no-Dog.png']]
      }
      else {
        this.tab = [["狗", '/img/Dog.png', '/img/no-Dog.png'], ["猫", '/img/cat.png', '/img/no-cat.png']]
      }
      this.getData(options.type,this.skip)
      this.setData({ show: true, options: this.tab,tabCur1:0}) 
    }
  },

  onReachBottom: function(){
    wx.showToast({
      title: '正在努力为主人找更多的品种',
      icon:"none"
    })
    this.getData(this.pet,this.skip)
  },

  search: function (e) {
    console.log(this.pet)
    wx.showToast({
      title: '正在努力查找中，请稍等。',
      icon: "none"
    })

    db.collection(this.pet).where(
      db.command.or([
        {
          term: {
            $regex: '.*' + e.detail.value.keyword + '.*',
            $options: 'i'
          }
        },
        {
          name: {
            $regex: '.*' + e.detail.value.keyword + '.*',
            $options: 'i'
          }
        }
      ])
      )
      .get()
      .then(res => {
        console.log(res.data)
        if (res.data.length != 0) {
          this.setData({ listData: res.data })
        }
        else {
          wx.showToast({
            title: '对不起主人，没找到Ta w(ﾟДﾟ)w',
            icon: "none"
          })
        }
      })
  },

  top:function(){
    wx.pageScrollTo({
    scrollTop: 0,
  })},
  tabSelect: function (e) {
    this.skip = 0 
    this.data.listData = []
    if (this.tab[e.currentTarget.dataset.index][0]=="猫"){
      this.pet = 'cat'
      this.getData('cat',this.skip)
      }
    else{
      this.pet = 'dog'
      this.getData('dog',this.skip)
      }

    this.setData({
      tabCur1: e.currentTarget.dataset.index
    })
  },

  pickup: function(e){
    if(this.opt.path=="load"){
      var term = e.currentTarget.dataset.term
      wx.setStorageSync("term", term)
      wx.navigateBack({
        url: '/pages/select/select'
      })
    }
  }   
})